package com.ruoyi.plus.pub.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.plus.constants.PlusDictConstants;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.plus.pub.domain.PubNoticePlus;
import com.ruoyi.plus.pub.domain.PubNoticeReceiver;
import com.ruoyi.plus.pub.mapper.PubNoticePlusMapper;
import com.ruoyi.plus.pub.mapper.PubNoticeReceiverMapper;
import com.ruoyi.plus.pub.service.IPubNoticePlusService;
import com.ruoyi.plus.pub.service.IPubNoticeReceiverService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 系统公告通知Service业务层处理
 *
 */
@Slf4j
@Service
public class PubNoticePlusServiceImpl extends ServiceImpl<PubNoticePlusMapper, PubNoticePlus> implements IPubNoticePlusService {

    @Autowired
    private PubNoticePlusMapper pubNoticePlusMapper;
    @Autowired
    private PubNoticeReceiverMapper pubNoticeReceiverMapper;

    @Autowired
    private IPubNoticeReceiverService noticeReceiverService;

    public PubNoticePlusServiceImpl() {
    }

    /**
     * 查询系统公告通知列表
     *
     * @param pubNoticePlus 系统公告通知
     * @return 系统公告通知
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<PubNoticePlus> selectPubNoticePlusList(PubNoticePlus pubNoticePlus) {
        return pubNoticePlusMapper.selectPubNoticePlusList(pubNoticePlus);
    }

    @Override
    public List<PubNoticePlus> apiGetNotices(PubNoticePlus pubNoticePlus) {
        return pubNoticePlusMapper.apiGetNotices(pubNoticePlus);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updatePubNoticePlus(PubNoticePlus pubNoticePlus) {
        String status = pubNoticePlus.getStatus();

        //1为未发布
        if (PlusDictConstants.NOTICE_PLUS_TYPE_PRIVATE.equals(pubNoticePlus.getType())
                && !PlusDictConstants.NOTICE_PLUS_STATUS_UN_RELEASE.equals(status)) {
            PubNoticeReceiver nr = new PubNoticeReceiver();
            nr.setNoticeId(pubNoticePlus.getId());
            nr.setNoticeStatus(status);
            pubNoticeReceiverMapper.updateNoticeStatus(nr);
        }
        if (PlusDictConstants.NOTICE_PLUS_STATUS_CANCEL.equals(status)) {
            PubNoticeReceiver nr = new PubNoticeReceiver();
            nr.setNoticeId(pubNoticePlus.getId());
            List<PubNoticeReceiver> pubNoticeReceivers = pubNoticeReceiverMapper.selectPubNoticeReceiverList(nr);
            List<PubNoticeReceiver> collect = pubNoticeReceivers.stream().map(e -> e.setReadStatus(PlusDictConstants.NOTICE_PLUS_READ_STATUS_UN_READ)).collect(Collectors.toList());
            noticeReceiverService.updateBatchById(collect);
        }
        return saveOrUpdate(pubNoticePlus);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeNotice(List<Long> list) {
        for (Long id : list) {
            pubNoticeReceiverMapper.deleteReceiversByNoticeId(id);
        }

        return removeByIds(list);
    }

    /**
     * 获取我的通知
     *
     * @param pubNoticePlus
     * @return
     */
    @Override
    public List<PubNoticePlus> myNotices(PubNoticePlus pubNoticePlus) {
        return pubNoticePlusMapper.myNotices(pubNoticePlus);
    }

    @Override
    public void timingNotice() {
        pubNoticePlusMapper.timingNotice("2");
        pubNoticePlusMapper.timingNotice("3");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean apiSaveNotice(List<Long> userIds, String title, String content) {
        if (userIds.isEmpty()) {
            log.info("发送日志结果为:{},用户id为空",false);
            return false;
        }

        PubNoticePlus pubNoticePlus = new PubNoticePlus();
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, +365);
        Date tomorrow = cal.getTime();
        pubNoticePlus.setType(PlusDictConstants.NOTICE_PLUS_TYPE_PRIVATE).setNoticeStartTime(DateUtils.getNowDate()).setContent(content)
                .setNoticeEndTime(tomorrow).setTitle(title).setStatus(PlusDictConstants.NOTICE_PLUS_STATUS_RELEASE);
        this.save(pubNoticePlus);
        List<PubNoticeReceiver> pubNoticeReceiverList =new ArrayList<>();
        userIds.forEach(e->{
            PubNoticeReceiver pubNoticeReceiver = new PubNoticeReceiver();
            pubNoticeReceiver.setUserId(e).setNoticeId(pubNoticePlus.getId()).setNoticeStatus(pubNoticePlus.getStatus())
                    .setReadStatus(PlusDictConstants.NOTICE_PLUS_READ_STATUS_UN_READ).setNoticeStartTime(pubNoticePlus.getNoticeStartTime())
                    .setNoticeEndTime(pubNoticePlus.getNoticeEndTime());
            pubNoticeReceiverList.add(pubNoticeReceiver);
        });
        boolean b = noticeReceiverService.saveBatch(pubNoticeReceiverList);
        log.info("发送日志结果为:{},用户id为{}",b,userIds.toString());
        return true;
    }

    /**
     * 一键已读
     * @param system 系统类型
     * @return
     */
    @Override
    public Boolean readAll(String system) {
        Long userId = SecurityUtils.getUserId();
        LambdaUpdateWrapper<PubNoticeReceiver> wrapper=new UpdateWrapper<PubNoticeReceiver>().lambda()
                .set(PubNoticeReceiver::getReadStatus, PlusDictConstants.NOTICE_PLUS_READ_STATUS_READ)
                .eq(PubNoticeReceiver::getUserId,userId)
                .eq(PubNoticeReceiver::getSystemType,system);
        noticeReceiverService.update(wrapper);
        return true;
    }

}
